package CBBOT::Server;

use strict;
use warnings;
use lib '/home/services/cbbot/irclib';
use lib '/home/services/cbbot/2.0/';
use Scalar::Util qw(looks_like_number);
use Time::Out qw(timeout);
use IO::Socket::INET;
use CBBOT::Config;

my $dbh	= CBBOT::Config::get_dbh();

sub voice_server {
	my($input, $channel) = @_;
	my $server = undef;

	if(!looks_like_number($input)) {
		my($trigger, $what) = split(/\s/, $input);
		if(looks_like_number($what)) {
			$server = $what;
		} else {
			my $setup = $dbh->selectrow_hashref("
				SELECT voiceserver FROM setup WHERE channel=?", undef, $channel);
			$server = $setup->{voiceserver};
		}
	} else {
		$server = $input;
	}

	if($server =~ /(\d+\.\d+\.\d+\.\d+):(\d+)/) {
		my($ip, $port) = ($1, $2);
		my($i, $socketdata, @return) = (0,'','');

		timeout 1 => sub {
			my $socket = IO::Socket::INET->new(
				Proto => "tcp",
				PeerAddr => $ip,
				PeerPort => 10011
			) or return("Can't connect to voiceserver: $!");

			$socket->send("use port=$port\n");
			$socket->send("clientlist\n");

			while(<$socket>) {
				$socketdata .= $_;
			}
		};

		my @players = $socketdata =~ /client_nickname=([A-Za-z0-9]{3,30})\sclient_type/g;
		foreach my $player (@players) {
			push(@return, $player);
			$i++;	
		}

		if($i > 0) {
 			push(@return, "-" x (8 + length($i)));	
			push(@return, "Totalt: $i");
		} else {
			push(@return, "Nobody online!");
		}
		return @return;

	} else {
		return "No voiceserver defined for this channel";
	}
}	

sub game_server {
	my($input, $channel, $type) = @_;
	my $server = undef;

	if(!looks_like_number($input)) {
		my($trigger, $what) = split(/\s/, $input);
		if(defined($what) && $what =~ /(\d+\.\d+\.\d+\.\d+):(\d+)/) {
			$server = $what;
		} else {
			my $setup = $dbh->selectrow_hashref("
				SELECT gameserver FROM setup WHERE channel=?", undef, $channel);
			$server = $setup->{gameserver};
		}
	} else {
		$server = $input;
	}

	if($server =~ /(\d+\.\d+\.\d+\.\d+):(\d+)/) {
		my($ip, $port) = ($1, $2);
		my @bestrank = ("", 0);
		my(@avgping, @return);
		my $i = 0;
		
		timeout 1 => sub {
			my $msg = "\xFF\xFF\xFF\xFFgetstatus\x00";
			my $socket = IO::Socket::INET->new(
				PeerAddr => $server,
				Proto => 'udp'
			) or return("Couldn't establish socket: $!");
	
			$socket->send($msg);
						
			while(<$socket>) {
				if($_ =~ /(\d+)\s(\d+)\s\"(.*?)\"/) {
					my($score, $ping, $nick) = ($1, $2, $3);
					push(@return, "$nick ($score)");
					if($bestrank[1] < $score) {
						$bestrank[1] = $score;
						$bestrank[0] = $nick;
					}
					$i++;
					push(@avgping, $ping);
				}
			}
		};

		if($i > 0) {	
			my $avgping = 0;
			for my $ping (@avgping) { 
				$avgping = $avgping + $ping;
			}
			$avgping = int($avgping / scalar(@avgping));
			if($type eq 'simple') {
				push(@return, $i);
			} else {		
				if($bestrank[1] > 0) { 
					push(@return, "$bestrank[0] is currently in the lead with $bestrank[1] points");
				}
				push(@return, "Average ping: $avgping ms");
				push(@return, "A total of $i player(s) online");
			}
		} else {
			push(@return, "Couldn't find any players :-(");
		}
		return @return;

	} else {
		return "No gameserver defined for this channel";
	}
}

sub notify_voice {
	my($msgref, $server) = @_;
	if($server =~ /(\d+\.\d+\.\d+\.\d+):(\d+)/) {
		my($ip, $port) = ($1, $2);
		# TEMP
		$ip = "127.0.0.1";
		my $socket = IO::Socket::INET->new(
			Proto => "tcp",
			PeerAddr => $ip,
			PeerPort => 10011
		) or return("Can't connect to voiceserver: $!");

		$socket->send("use port=$port\n");
		$socket->send("login serveradmin kh4qa3\n");
		$socket->send("clientupdate client_nickname=kylling\n");		

		my $msg;
		my $i = 1;
		foreach my $y (@{$msgref}) {
			next if $y eq '';
			$y =~ s/\s/\\s/g;
			if($i == 1) {
				$y .= '\s\s;-)';
				$socket->send("sendtextmessage targetmode=2 target=9 msg=[b][color=#0000FF]".$y."[/color][/b]\n");
				$i++;
			} else {
				$socket->send("sendtextmessage targetmode=2 target=9 msg=[color=#0000FF]".$y."[/color]\n");
			}
		}
	}
}

1;

